<template>
  <page-layout>
    <a-row :gutter="[10, 10]">
      <a-col :span="24">
        <a-card>
          <footer-button :buttons="formState.buttons" />
          <a-form ref="formRef" :rules="formRules" :model="modelForm.data" :labelCol="{ span: 9 }">
            <a-row>
              <a-col :span="8">
                <a-form-item
                  label="助教编码"
                  name="code"
                >
                  <a-input readonly v-model:value="modelForm.data.code" placeholder="自动生成"/>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :label="t('ta-manage.label.heName')"
                  v-bind="validateInfos.taName"
                  name="taName"
                >
                  <a-input v-model:value="modelForm.data.taName" :placeholder="t('placeholder.pleaseEnter')"/>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :label="t('ta-manage.label.gender')"
                  v-bind="validateInfos.taSex"
                  name="taSex"
                >
                  <a-select v-model:value="modelForm.data.taSex">
                    <a-select-option
                      v-for="(item, index) in dictLists.data[dictEnum.SEX]"
                      :key="index"
                      :value="item.value"
                      >{{ item.label }}</a-select-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :label="t('ta-manage.label.dateOfBirth')"
                  ref="taBirthDate"
                  name="taBirthDate"
                >
                  <a-date-picker
                    style="width: 100%"
                    v-model:value="modelForm.data.taBirthDate"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    placeholder="年月日"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="8">
                <a-form-item
                  :label="t('ta-manage.label.major')"
                  ref="taMajor"
                  name="taMajor"
                >
                  <a-input v-model:value="modelForm.data.taMajor" :placeholder="t('placeholder.pleaseEnter')"/>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :label="t('ta-manage.label.phone')"
                  ref="taPhone"
                  name="taPhone"
                >
                  <a-input maxlength="11" v-model:value="modelForm.data.taPhone" :placeholder="t('placeholder.pleaseEnter')"/>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :label="t('ta-manage.label.email')"
                  name="taEmail"
                >
                  <a-input maxlength="30" v-model:value="modelForm.data.taEmail" :placeholder="t('placeholder.pleaseEnter')"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="8">
                <a-form-item
                  :label="t('ta-manage.label.certificateType')"
                  v-bind="validateInfos.taDocumentType"
                  name="taDocumentType"
                >
                  <a-select v-model:value="modelForm.data.taDocumentType">
                    <a-select-option
                      v-for="(item, index) in dictLists.data[
                        dictEnum.DOCUMENT_TYPE
                      ]"
                      :key="index"
                      :value="item.value"
                      >{{ item.label }}</a-select-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :label="t('ta-manage.label.idNumber')"
                  name="taCertificateNo"
                >
                  <a-input
                    v-model:value="modelForm.data.taCertificateNo"
                    :placeholder="t('placeholder.pleaseEnter')"
                    maxlength="20"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :label="t('ta-manage.label.school')"
                  ref="schName"
                  name="schName"
                >
                  <a-input readonly v-model:value="modelForm.data.schName" :placeholder="t('placeholder.pleaseSelect')">
                    <template #addonAfter>
                      <div
                        class="primary-color cursor-pointer"
                        @click="openDialog('universityVisible')"
                      >
                        {{ t('button.select') }}
                      </div>
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="24">
                <a-form-item
                  :label="t('ta-manage.label.responsibleForTheSubject')"
                  ref="responsibleAccount"
                  :labelCol="{ span: 3 }"
                  name="responsibleAccount"
                >
                  <a-textarea
                    :auto-size="{ minRows: 2, maxRows: 6 }"
                    :placeholder="t('placeholder.pleaseEnter')"
                    :maxlength="500"
                    v-model:value="modelForm.data.responsibleAccount"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-card>
        <div class="pre-title">
          {{ t("ta-manage.title.attachmentInformation") }}
        </div>
        <a-card>
          <div class="up-file">
            <span class="label">{{ t("ta-manage.title.contract") }}：</span>
            <a-upload
              name="file"
              :showUploadList="false"
              :customRequest="(data) => handleUpload(data, 'contract')"
            >
              <a-button>{{ t("ta-manage.title.uploadFiles") }}</a-button>
              <p
                v-for="item in contractFiles"
                :key="item.fileId"
                class="mt-10"
              >
                {{ item.name }}
                <DeleteOutlined
                  class="ml-10 cursor-pointer"
                  @click.prevent.stop="() => handleDelUpload(item.fileId)"
                />
              </p>
            </a-upload>
          </div>
        </a-card>
      </a-col>
    </a-row>
    <school
      :visible="formState.universityVisible"
      @close="closeDialog"
      @submitSchool="selectUniversity"
    />
  </page-layout>
</template>

<script>
import school from "./modal/index.vue";

import { save, details, upload, adjust, dictionary } from "@/api/module/ta";
import { useI18n } from "vue-i18n";

import { Form, message, modal } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { useRouter, useRoute } from "vue-router";
import mixin from '@/mixins'

import dictEnum from "@/const/dict";
import { getDictByCodesReturnObj } from "@/tools/get-dict";
import { 
  emailPattern, // 邮箱
  passportPattern, // 护照
  businessPattern, // 营业执照
  idCardPattern, // 身份证号
  phoneCardPattern, // 电话号码
} from "@/utils/validator.js"

import {
  defineComponent,
  reactive,
  toRaw,
  createVNode,
  computed,
  onMounted,
  ref,
  onActivated,
} from "vue";
import moment from "moment";
const useForm = Form.useForm;
export default defineComponent({
  name: "ta-manage-list",
  components: {
    school,
  },

  setup() {
    const { returnRoute } = mixin.setup()
    const { t } = useI18n();
    const router = useRouter();
    const route = useRoute();
    const formRef = ref();
    const contractFiles = computed(() =>
      modelForm.data.files.filter((v) => v.type === "contract")
    );

    const formState = reactive({
      universityVisible: false,
      sexList: [],
      buttons: [
        {
          name: "save",
          event: () => handleSave(),
          type: "primary",
          code: "",
        },
        {
          name: "reset",
          event: () => handleReset(),
          code: "",
        },
      ]
    });
    const labelCol = { span: 3, offset: 12 };
    const wrapperCol = { span: 14 };

    let dictLists = reactive({
      data: {},
    });
    let modelForm = reactive({
      data: {
        taDocumentType: '1',
        files: [],
      },
    });
    const fileList = reactive([]);
    const formRules = reactive({
      taName: [{ required: true, message: "请输入TA姓名" }],
      taEmail: [{ required: true, validator: async (rules, value) => {
        if (!value) return Promise.reject('请输入Email')
        if (!emailPattern.test(value)) {
          return Promise.reject('请输入正确的邮箱地址')
        } else {
          return Promise.resolve()
        }
      }, trigger: 'blur' }],
      taPhone: [{ required: false, validator: async (rules, value) => {
        if (!value) return Promise.resolve()
        if (!phoneCardPattern.test(value)) {
          return Promise.reject('请输入正确电话号码')
        } else {
          return Promise.resolve()
        }
      }, trigger: 'blur' }],
      taSex: [{ required: true, message: "请输入性别" }],
      taDocumentType: [{ required: true, message: "请选择证件类型" }],
      taCertificateNo: [{ required: true, validator: (rules, value) => {
        if (!value) return Promise.reject('请输入证件号')
        const num = modelForm.data.taDocumentType
        let result = false;
        switch (Number(num)) {
          case 1: 
            result = idCardPattern.test(value)
            break;
          case 2:
            result = passportPattern.test(value)
            break;
          case 3:
            result = businessPattern.test(value)
            break;
        }
        if (result) {
          return Promise.resolve()
        } else {
          return Promise.reject('请输入正确的证件号码')
        }
      }, trigger: 'blur' }],
    });
    const { resetFields, validate, validateInfos } = useForm(
      modelForm.data,
      formRules
    );
    const openDialog = (type) => {
      formState[type] = true;
    };
    const handleChange = (info) => {
      const arr = info.fileList.filter((v) => v.status !== "error");
      if (arr && arr.length) {
        modelForm.data.files = arr.map((item) => {
          return {
            url: item.response ? item.response.path || "" : "",
            businessType: "ta",
            type: 1,
          };
        });
      }
    };

    const closeDialog = (type) => {
      formState[type] = false;
    };

    const selectUniversity = (value) => {
      formState["universityVisible"] = false;
      if (value) {
        modelForm.data.schId = value.id;
        modelForm.data.schName = value.schoolEnName;
      }
    };

    const handleUpload = (data, type) => {
      const formData = new FormData();
      formData.append("file", data.file);
      upload(formData).then((res) => {
        if (res.code === 500) {
          message.error({ content: "上传附件失败" });
          data.onError();
        } else {
          const { path: url, id: fileId, remark, name } = res.data;
          modelForm.data.files.push({ type, url, fileId, remark, name });
          data.onSuccess(res.data);
        }
      });
    };

    // 获取详情
    const getDetails = (id) => {
      if (!id) return;
      return details({ id }).then((res) => {
        if (res.success) {
          res.data.taBirthDate = res.data.taBirthDate
            ? moment(res.data.taBirthDate).format("YYYY-MM-DD")
            : "";
          modelForm.data = reactive({
            ...modelForm.data,
            ...res.data,
          });
        }
      });
    };

    const getDctionary = () => {
      return dictionary({}).then((res) => {
        if (res.success) {
          formState.sexList = res.data;
        }
      });
    };

    // 保存
    const handleSave = () => {
      formRef.value.validate().then(() => {
        const result = toRaw(modelForm.data);
        result.taBirthDate = result.taBirthDate ? new Date(result.taBirthDate).getTime() : null
        if (result.id) {
          adjust(result)
            .then((res) => {
              if (res.success) {
                message
                  .success({ content: "保存成功", duration: 1 })
                  .then(() => {
                    returnRoute()
                    formRef.value.resetFields();
                  });
              } else {
                message.warning({ content: "保存失败", duration: 1 });
              }
            })
            .catch((err) => {
              console.log("err: ", err);
              message.warning({ content: "保存失败", duration: 1 });
            });
        } else {
          save(result)
            .then((res) => {
              if (res.success) {
                message
                  .success({ content: "保存成功", duration: 1 })
                  .then(() => {
                    returnRoute()
                    formRef.value.resetFields();
                  });
              } else {
                message.warning({ content: "保存失败", duration: 1 });
              }
            })
            .catch((err) => {
              message.warning({ content: "保存失败", duration: 1 });
            });
        }
      });
    };

    const handleReset = () => {
      formRef.value.resetFields();
    };

    const handleDelUpload = (fileId) => {
      modelForm.data.files = modelForm.data.files.filter(
        (v) => v.fileId !== fileId
      );
    };
    onActivated(() => {
      const result = route.query;
      if (result && result.id) {
        getDetails(result.id);
      } else {
        modelForm.data = {
          taName: "",
          taSex: "0",
          taDocumentType: "1",
          taCertificateNo: "",
          files: [],
        };
      }
      getDctionary();
    });
    onMounted(async () => {
      dictLists.data = await getDictByCodesReturnObj([
        dictEnum.SEX,
        dictEnum.DOCUMENT_TYPE,
      ]);
    });
    return {
      t,
      modelForm,
      formRules,
      labelCol,
      wrapperCol,
      openDialog,
      formState,
      handleChange,
      selectUniversity,
      closeDialog,
      handleSave,
      validateInfos,
      resetFields,
      handleUpload,
      fileList,
      dictLists,
      dictEnum,
      formRef,
      handleReset,
      contractFiles,
      handleDelUpload,
    };
  },
});
</script>

<style lang="less" scoped>
.page-head {
  /deep/ .ant-page-header-heading-title {
    color: #2d8cf0;
  }
}

.pre-title {
  padding: 10px 25px;
  background-color: #f5f5f5;
  color: #555;
}

.up-file {
  width: 65%;
  display: flex;
  flex-wrap: nowrap;
  .label {
    width: 65px !important;
    line-height: 30px;
  }
  span:last-child {
    margin-left: 5px;
  }

  /deep/ .ant-upload-list-item-card-actions {
    right: -10px;
  }
}
</style>